<?php
namespace App\Http\Controllers\Api\V1;

use App\Models\Order;
use App\Models\Product;
use App\Models\UserProduct;
use App\TraitHelper\RequestHelper;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use EasyWeChat\Payment\Order as WxOrder;
use Illuminate\Support\Facades\Log;
use WxPayConfig;

/**
 * Created by PhpStorm.
 * User: xinghuo
 * Date: 2017/7/11
 * Time: 上午12:53
 */
class OrderController
{
    use RequestHelper;

    public function create(Request $request)
    {
        $user = $this->getLoginUserInfo($request);
        $validator = \Validator::make($request->all(), [
            'mobile' => 'required',
            'username' => 'required',
            'address' => 'required',
            'street' => 'required',
            'tag' => 'required',
            'number' => 'required|integer|digits_between:1,100000',
            'pay_type' => 'required',
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return $this->formatJson(false, [], $messages->first());
        }
        $product = Product::where('id', '>', 0)->first();
        if (!$product) {
            return $this->formatJson(false, [], "商品不存在!");
        }

        $order = new Order();
        $sn = Order::getSn($user['id']);
        $order->sn = $sn;
        $order->user_id = $user['id'];
        $order->mobile = $request->get('mobile');
        $order->username = $request->get('username');
        $order->address = $request->get('address');
        $order->street = $request->get('street');
        $order->tag = $request->get('tag');
        $order->number = $request->get('number');
        $order->price = Order::getOrderPrice($request->get('number'));

        $order->product_id = $product->id;
        $order->product_name = $product->title;
        $order->pay_type = $request->get('pay_type');
        $order->memo = $request->get('memo');
        $order->parent_user_id = $request->get('_ig');
        if ($order->parent_user_id) {
            $order->commission = Product::$commission_price;
        }

        $result = $order->save();
        if ($result && $order->pay_type == Order::PAY_TYPE_DOWN_LINE) {
            $userProduct = UserProduct::whereOrderId($order->id)->first();
            if (!$userProduct) {
                $userProduct = new UserProduct();
            }
            $userProduct->status = UserProduct::STATUS_WAIT_INSTALL;
            $userProduct->order_id = $order->id;
            $userProduct->user_id = $order->user_id;
            $userProduct->product_id = Product::first()->id;
            $userProduct->save();
        }
        return $this->formatJson(true, ['order_id' => $sn]);
    }

    public function make(Request $request)
    {

        $user = $this->getLoginUserInfo($request);
        $sn = $request->get('sn');
        $order = Order::where('sn', $sn)->first();
        if (!$order) {
            return $this->formatJson(false, ['e' => 'OUT_TRADE_NO_USED'], "订单不存在!");
        }

        if ($order->pay_time) {
            return $this->formatJson(false, ['e' => 'OUT_TRADE_NO_USED'], "订单已付款!");
        }
        $order->pay_type = Order::PAY_TYPE_WECHAT;
        $order->save();
        $orderInfo = $order->toArray();
        $orderInfo['price'] *= 100;
        if (Order::isTestUser($user['id'])) {
            $orderInfo['price'] = 1;
        }

        $user['open_id'] = $request->get('open_id');

        $wechat = app('wechat');
        $attributes = [
            'openid' => $user['open_id'],
            'body' => '净水器设备',
            'detail' => '净水器设备 ',
            'time_expire' => '20361227091010',//20年过期
            'total_fee' => $orderInfo['price'],//微信的费用已整数位单位. 个位数后面是分
            'trade_type' => WxOrder::JSAPI,
            'notify_url' => url('/payNotify/wechat'),
            'out_trade_no' => $sn
        ];

        if (isset($order->out_trade_no) && substr($order->out_trade_no, 0, 2) == 'wx') {
            $prepay_id = $order->out_trade_no;
        } else {
            $wxOrder = new WxOrder($attributes);
            $result = $wechat->payment->prepare($wxOrder);
            $prepay_id = $result->prepay_id;
            if ($prepay_id) {
                $order->out_trade_no = $prepay_id;
                $order->save();
            }
        }
        if ($prepay_id) {
            $json = $wechat->payment->configForPayment($prepay_id, false);
            return $this->formatJson(200, ['wx' => $json]);
        } else {
            $expire = $result->err_code == 'OUT_TRADE_NO_USED';
            if ($expire) {
                return $this->formatJson(500, ['e' => 'OUT_TRADE_NO_USED'], "订单不存在!");
            } else {
                return $this->formatJson(500, ['e' => $result->return_msg], $result->return_msg);
            }
        }
    }

    public function makeWxApp(Request $request)
    {

        $user = $this->getLoginUserInfo($request);
        $sn = $request->get('sn');
        $order = Order::where('sn', $sn)->first();
        if (!$order) {
            return $this->formatJson(false, ['e' => 'OUT_TRADE_NO_USED'], "订单不存在!");
        }

        if ($order->pay_time) {
            return $this->formatJson(false, ['e' => 'OUT_TRADE_NO_USED'], "订单已付款!");
        }
        $order->pay_type = Order::PAY_TYPE_WECHAT;
        $order->save();
        $orderInfo = $order->toArray();
        $orderInfo['price'] *= 100;
        if (Order::isTestUser($user['id'])) {
            $orderInfo['price'] = 1;
        }

        /**
         * @var Application $wechat
         */


        if (isset($order->out_trade_no) && substr($order->out_trade_no, 0, 2) == 'wx') {
            $prepay_id = $order->out_trade_no;
        } else {
            $input = new \WxPayUnifiedOrder();
            $input->SetAppid("wxa9f8f372188a6867");
            $input->SetMch_id("1487600712");
            $input->SetBody("净水器设备");  //设置商品或支付单简要描述
            $input->SetAttach('');    //设置附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
            $input->SetOut_trade_no($sn);  //设置商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
            $input->SetTotal_fee( $orderInfo['price'] );  //设置订单总金额，只能为整数，详见支付金额
            $input->SetTime_start(date("YmdHis"));  //设置订单生成时间，格式为yyyyMMddHHmmss
            $input->SetTime_expire('20361227091010');    //设置订单失效时间，格式为yyyyMMddHHmmss
            $input->SetGoods_tag("tag");  //设置商品标记，代金券或立减优惠功能的参数，说明详见代金券或立减优惠
            $input->SetNotify_url(url('/payNotify/wechatApp'));  //设置接收微信支付异步通知回调地址
            $input->SetTrade_type("APP");  //设置类型如下：JSAPI，NATIVE，APP
            $order_data = \WxPayApi::unifiedOrder($input);  //统一下单payNotify.wechatApp
            $prepay_id = $order_data['prepay_id'];
            if ($prepay_id) {
                $order->out_trade_no = $prepay_id;
                $order->save();
            }
        }
        if ($prepay_id) {
            $order_data['appid'] = 'wxa9f8f372188a6867';
            $order_data['partnerid'] = '1487600712';
            $order_data['prepay_id'] = $prepay_id;
            $str = 'appid=' . $order_data['appid'] . '&noncestr=' . \WxPayApi::getNonceStr() . '&package=Sign=WXPay&partnerid=' . WxPayConfig::MCHID . '&prepayid=' . $prepay_id . '&timestamp=' . time();
            $sign = strtoupper(md5($str . '&key=' . WxPayConfig::KEY));
            $query = [];
            parse_str($str, $query);
            $query['sign'] = $sign;
            return $this->formatJson(true, $query);
        } else {
            return $this->formatJson(false, $order_data);
        }
    }

    public function makeAppAlipay(Request $request)
    {

        $user = $this->getLoginUserInfo($request);
        $sn = $request->input('sn');
        $order = Order::where('sn', $sn)->first();
        if (!$order) {
            return $this->formatJson(false, ['e' => 'OUT_TRADE_NO_USED'], "订单不存在!");
        }

        if ($order->pay_time) {
            return $this->formatJson(false, ['e' => 'OUT_TRADE_NO_USED'], "订单已付款!");
        }
        $order->pay_type = Order::PAY_TYPE_ALIPAY;
        $order->save();

        $aop = new \AopClient();
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = config('alipay.app_id');
        $aop->rsaPrivateKey = str_replace("\r\n", "", file_get_contents(config('alipay.merchant_private_key')));
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = str_replace("\r\n", "", file_get_contents(config('alipay.alipay_public_key')));
        $request = new \AlipayTradeAppPayRequest();
        $bizContent['body'] = $order->product_name ? $order->product_name : "芯好水好订单费用";
        $bizContent['subject'] = 'App支付';
//        $bizContent['out_trade_no'] = "YY-".time();
        $bizContent['out_trade_no'] = $order->sn;
        $bizContent['timeout_express'] = '30m';
        if (Order::isTestUser($user['id'])) {
            $bizContent['total_amount'] = '0.01';
        } else {
            $bizContent['total_amount'] = $order->price;
        }
        $bizContent['product_code'] = 'QUICK_MSECURITY_PAY';
        $request->setNotifyUrl(route("payNotify.alipayApp"));
        $request->setBizContent(json_encode($bizContent));
        //这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
//        $alipay = app('alipay.mobile');
////        $alipay->setOutTradeNo($order->sn);
//        $alipay->setOutTradeNo("yy-".time());
////        $alipay->setTotalFee($order->price);
//        $alipay->setTotalFee('0.01');
//        $alipay->setSubject($order->product_name);
//        $alipay->setBody($order->product_name);
//        // 返回签名后的支付参数给支付宝移动端的SDK。

        return $this->formatJson(true, ['ali' => $response]);
    }

}